14. Exercise: Adding Support for the Up Button
L3 22 Navigating Up SC
To add support for the up button, we first need to make sure our Activity has an ActionBar. We’ve already done this piece of the work for you, but to review:
1. Link the NavController to the ActionBar with NavigationUI.setupWithNavController.
Let's move to MainActivity. We need to find the NavController. Since we’re in the Activity now, we’ll use the alternate method of finding the controller from the ID of our NavHostFragment using the KTX extension function.
val navController = this.findNavController(R.id.myNavHostFragment)
Link the NavController to our ActionBar.
NavigationUI.setupActionBarWithNavController(this, navController)
** 2. Override the onSupportNavigateUp method from the activity and call navigateUp in nav controller.**
Finally, we need to have the Activity handle the navigateUp action from our Activity. To do this we override onSupportNavigateUp, find the nav controller, and then we call navigateUp().
override fun onSupportNavigateUp(): Boolean {
val navController = this.findNavController(R.id.myNavHostFragment)
return navController.navigateUp()
}
If you want to start at this step, you can download this exercise code from: Step.05-Exercise-Adding-Support-for-the-Up-Button.
You will find plenty of //TODO comments to help you complete this exercise, and if you get stuck, go back and watch the video again.
Once you’re done, you can check your solution against the solution we’ve provided here Step.05-Solution-Adding-Support-for-the-Up-Button or git diff.
Task Description:
Check the steps below as you implement them to complete this exercise.
Task Feedback:
And you can navigate up!
Solution: Step.05-Solution-Adding-Support-for-the-Up-Button or git diff